package com.darsystems.foghourz.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.rpc.AsyncCallback;


public class FBAuthorizer implements Authorizer {

	public static final String TOKEN_COOKIE_NAME = "fogBugzToken";

	private final FogBugzServiceAsync fogbugzService = GWT
												.create(FogBugzService.class);
	
	private String token;
	
	public void checkLoginStatus(final AuthorizeCallback callback) {
		//first, check if the cookie has a token
		final String existingToken = Cookies.getCookie(TOKEN_COOKIE_NAME);
		
		if(existingToken != null)
		{
			//try the token - see if it still works
			fogbugzService.executeCommand(existingToken, "listPeople", "", 
				new AsyncCallback<FBResponse>(){
					public void onFailure(Throwable caught) {
						// Show the RPC error message to the user
						callback.onFailure(caught);
					}

					public void onSuccess(FBResponse result) {
						if(result.getErrorCode() == 3)
						{
							callback.onNotLoggedIn(getLoginUrl());
						}
						else
						{
							token = existingToken;
							callback.onLoggedIn(GWT.getHostPageBaseURL() + "FBLogout.html?token=" + token);
						}
					}
				});
		}
		else
		{
			callback.onNotLoggedIn(getLoginUrl());
		}
	}
	
	public String getToken()
	{
		return token;
	}

	public String getName()
	{
		return "FogBugz";
	}
	
	public boolean getAutoRedirect()
	{
		return true;
	}
	
	private String getLoginUrl()
	{
		return GWT.getHostPageBaseURL() + "FBLogin.html";
	}
}
